import { Handlers } from "$fresh/server.ts";
import { getDbClient } from "../../../utils/db.ts";
import { AdminState } from "../../_middleware.ts";

export const handler: Handlers<null, AdminState> = {
  async POST(req, ctx) {
    // 检查管理员权限
    if (!ctx.state.isAdmin) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { "Content-Type": "application/json" }
      });
    }

    try {
      const form = await req.formData();
      const postId = form.get("post_id") as string;

      // 验证
      if (!postId) {
        return new Response(JSON.stringify({ error: "Post ID is required" }), {
          status: 400,
          headers: { "Content-Type": "application/json" }
        });
      }

      // 从数据库删除
      const client = await getDbClient();
      try {
        await client.execute(
          "DELETE FROM posts WHERE id = ?",
          [postId]
        );

        // 重定向到首页并显示成功消息
        const headers = new Headers();
        headers.set("Location", "/?deleted=true");
        return new Response(null, {
          status: 303,
          headers
        });
      } finally {
        await client.close();
      }
    } catch (error) {
      console.error("Error deleting post:", error);
      return new Response(JSON.stringify({ error: "Failed to delete post" }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
}; 